package caddy

import (
	"bytes"
	"context"
	"fmt"
	"os"
	"path/filepath"
)

func (cls *Caddy) ApplyConfig(_ context.Context) error {
	// 清理目录
	if err := os.RemoveAll(configFolder); nil != err {
		return err
	}

	// 重建目录
	if err := os.MkdirAll(configLoadPath, 0755); nil != err {
		return err
	}

	cls.LockConfig()
	defer cls.UnlockConfig()

	main, err := os.OpenFile(configFilePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	if nil != err {
		return err
	}

	defer func() {
		_ = main.Close()
	}()

	if _, err := main.WriteString(fmt.Sprintf("import %s/*\n", configLoadPath)); nil != err {
		return err
	}

	for hostname, website := range cls.GetConfig().Websites {
		wf, err := os.OpenFile(filepath.Join(configLoadPath, hostname), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
		if nil != err {
			return err
		}

		var builder = new(bytes.Buffer)

		var protocol = "http"
		if website.Tls.Enable {
			protocol = "https"
		}

		if _, err := builder.WriteString(fmt.Sprintf("%s://%s {\n", protocol, hostname)); nil != err {
			return err
		}

		if website.Tls.Custom {
			if _, err := builder.WriteString(fmt.Sprintf("\ttls %s %s\n", website.Tls.CertPath, website.Tls.KeyPath)); nil != err {
				return err
			}
		}

		for _, reverse := range website.Reverses {
			if _, err := builder.WriteString(fmt.Sprintf("\treverse_proxy %s %s\n", reverse.Path, reverse.Target)); nil != err {
				return err
			}
		}

		if _, err := builder.WriteRune('}'); nil != err {
			return err
		}

		if _, err := wf.Write(builder.Bytes()); nil != err {
			return err
		}

		if err := wf.Close(); nil != err {
			return err
		}
	}

	return nil
}
